package com.colin.dubbo.util;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtils {

    /**
     * javaBean转为map
     */
    public static Map<String, Object> bean2Map(Object bean) throws Exception{
        if(bean != null){
            Map<String, Object> returnMap = new HashMap<>();
            Class<?> beanClass = bean.getClass();
            BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            if(propertyDescriptors != null){
                for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                    if (propertyDescriptor != null) {
                        String name = propertyDescriptor.getName();
                        if(!"class".equals(name)){
                            Method readMethod = propertyDescriptor.getReadMethod();
                            Object result = readMethod.invoke(bean);
                            if (result != null && !"".equals(result)) {
                                returnMap.put(name, result);
                            }
                        }
                    }
                }
            }
            return returnMap.size() > 0 ? returnMap : null;
        }
        return null;
    }
    
}
